package hud;

import static org.lwjgl.opengl.GL11.GL_BLEND;
import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA;
import static org.lwjgl.opengl.GL11.glBlendFunc;
import static org.lwjgl.opengl.GL11.glDisable;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glVertex2f;

import org.lwjgl.opengl.GL11;

import level.Level;
import entity.Camera;
import entity.characters.Player;

/**
 * @author Jevgeni Krutov
 *
 */
public class Hud {
	private static final float DEF_ALPHA = 0.3f;
	private static final float DEF_CROSSHAIR_ALPHA = 0.75f;
	
	private Player player;
	private Camera camera;
	private Level level;
	private int resX;
	private int resY;
	
	public Hud(Player player, Camera camera,  Level level, int resX, int resY) {
		setResolution(resX, resY);
		this.player = player;
		this.level = level;
		this.camera = camera;
	}
	
	public void drawHud() {
		if(player == null || !player.isAlive() || camera.isFreeFloatingMode()) {
			return;
		}
		
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		
		GL11.glMatrixMode(GL11.GL_PROJECTION);
		GL11.glLoadIdentity();
		GL11.glOrtho(0, resX, 0, resY, 1, -1);
		GL11.glMatrixMode(GL11.GL_MODELVIEW);
		
		GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);  
		
		drawCrosshair();
		drawAmmo();
		
		drawHealthBar();
		
		glDisable(GL_BLEND);
	}
	
	public void setResolution(int resX, int resY) {
		this.resX = resX;
		this.resY = resY;
	}
	
	
	private void drawCrosshair() {
		GL11.glColor4f(1f, 1f, 1f, DEF_CROSSHAIR_ALPHA);
		
		GL11.glBegin(GL11.GL_QUADS);
			glVertex2f(resX/2,		resY/2);
			glVertex2f(resX/2 + 2,	resY/2);
			glVertex2f(resX/2 + 2,	resY/2 + 2);
			glVertex2f(resX/2,		resY/2 + 2);
		GL11.glEnd();
	}
	
	private void drawHealthBar() {
		float healthExtent = player.getHealthExtent();
		
		GL11.glColor4f(1 - healthExtent, healthExtent, 0f, DEF_ALPHA);
		
		GL11.glBegin(GL11.GL_QUADS);
			glVertex2f(60,										25);
			glVertex2f(60 + healthExtent * (resX - 10 - 60),	25);
			glVertex2f(60 + healthExtent * (resX - 10 - 60),	40);
			glVertex2f(60,										40);
		GL11.glEnd();
	}
	
	private void drawAmmo() {
		GL11.glColor4f(1f, 0.65f, 0f, DEF_ALPHA);
		
		for(int i = 0; i < player.getWeapon().getAmmo(); i++) {
			drawAmmoElement(i);
		}
	}

	private void drawAmmoElement(int i) {
		GL11.glBegin(GL11.GL_QUADS);
			glVertex2f(30 * i + 10,	resY - 10);
			glVertex2f(30 * i + 10,	resY - 10 - 30);
			glVertex2f(30 * i + 30,	resY - 10 - 30);
			glVertex2f(30 * i + 30,	resY - 10);
		GL11.glEnd();
	}
}
